package com.example.MastAndSlave.configer;

import com.example.MastAndSlave.domain.DBTypeEnum;
import com.example.MastAndSlave.domain.MyRoutingDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.slave1")
    public DataSource  slave1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.slave2")
    public DataSource  slave2DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.master")
    public DataSource  masterDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    public DataSource myRoutingDataSource(@Qualifier("slave1DataSource") DataSource slave1,
                                          @Qualifier("slave2DataSource") DataSource slave2,
                                          @Qualifier("masterDataSource") DataSource master){
        Map<Object,Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put(DBTypeEnum.SLAVE1,slave1);
        dataSourceMap.put(DBTypeEnum.SLAVE2,slave2);
        dataSourceMap.put(DBTypeEnum.MASTER,master);
        MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
        myRoutingDataSource.setDefaultTargetDataSource(master);
        myRoutingDataSource.setTargetDataSources(dataSourceMap);
        return myRoutingDataSource;
    }
}
